package com.hm.plugin.validate.handler;

import java.io.InputStream;
import java.lang.reflect.Field;
import java.text.MessageFormat;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.util.StringUtils;

import com.hm.common.annotation.Validate;
import com.hm.common.annotation.ValidateElement;
import com.hm.common.annotation.ValidateElementSize;

/**
 * @author shishun.wang
 * @date 下午2:30:53 2016年5月30日
 * @version 1.0
 * @describe
 */
public class ValidateUtil {

	public static <T> boolean validate(T entity) throws Exception {
		try {
			Class<? extends Object> objClass = entity.getClass();
			Validate annotation = objClass.getAnnotation(Validate.class);
			if (null != annotation) {
				
				InputStream inputStream = objClass.getResourceAsStream(annotation.value());
				Properties properties = new Properties();
				properties.load(inputStream);
				
				Field[] fields = objClass.getDeclaredFields();
				for (Field field : fields) {
					ValidateElement validateElement = field.getAnnotation(ValidateElement.class);
					if (null != validateElement) {// 需要验证的字段属性
						field.setAccessible(true);
						checkValidateElement(properties, field, validateElement, entity);
					}
				}
			}
		} catch (SecurityException e) {
			e.printStackTrace();
		}
		return true;
	}

	private static <T> void checkValidateElement(Properties properties, Field field, ValidateElement validateElement,
			T entity) throws Exception {
		Object obj = field.get(entity);
		String fieldName = field.getName();

		if (validateElement.required()) {// 验证必填项
			String msg = null;
			
			ValidateElementSize size = validateElement.size();
			if (null != size) {// 验证表单属性的长度
				msg = checkValidateElementSize(size, properties, fieldName, obj);
			}else{//只是验证是否为空
				if (null == obj) {
					msg = properties.getProperty(fieldName);
				}
			}
			
			String regex = validateElement.regex();
			if(!StringUtils.isEmpty(regex)){//正则表达式匹配
				Pattern pattern = Pattern.compile(regex);
				Matcher matcher = pattern.matcher(obj + "");
				if(!matcher.matches()){
					msg = properties.getProperty("DATA_FORMAT_MISMATCHING");//数据格式不匹配
				}
			}
			
			if(null != msg){
				throw new Exception("["+fieldName+"]" + msg);
			}
		}
	}
	
	private static String checkValidateElementSize(ValidateElementSize size,Properties properties,String fieldName,Object obj){
		String msg = null;
		String fileData = obj + "";
		
		int length = size.length();
		if (-1 != length) {// 判断固定长度
			if(fileData.length() != length){
				msg = MessageFormat.format(properties.getProperty(fieldName), length);
			}
		}else{
			if(fileData.length() > size.maxSize() || fileData.length() < size.minSize()){
				msg = MessageFormat.format(properties.getProperty(fieldName), size.minSize(),size.maxSize());
			}
		}
		
		return msg;
	}
}
